#include <sys/wait.h>
#include "../ourhdr.h"

/**
 * 用popen向分页程序传送文件
 * popen 创建一个管道, fork一个子进程
 * bourne shell下
 * sh -c ls *.c 
 * 等同于 
 * fp = popen("ls *.c", "r")
 * 
 */

#define PAGER "${PAGER:-more}"

int main(int argc, char *argv[])
{
    char line[MAXLINE];
    FILE *fpin, *fpout;
    if(argc != 2)
    {
        err_quit("usage : ipc04.cmd <pathname>");
    }
    if((fpin = fopen(argv[1], "r"))==NULL)
    {
        err_sys("can't open %s", argv[1]);
    }
    if((fpout = popen(PAGER,"w")) == NULL)
    {
        err_sys("popen error");
    }

    while(fgets(line,MAXLINE, fpin)!=NULL)
    {
        if(fputs(line, fpout) == EOF)
        {
            err_sys("fputs error to pipe");
        }
    }

    if(ferror(fpin))
    {
        err_sys("fgets error");
    }
    if(pclose(fpout) == -1)
    {
        err_sys("pclose error");
    }
    exit(0);
}
